package mark.tom.gear.base.utils

import android.annotation.SuppressLint
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.os.Build
import androidx.annotation.NonNull
import java.security.MessageDigest

/**
 * @Description: 安装包工具类
 * @Author: ttmk110@163.com
 * @Package: mark.tom.gear.base.utils
 * @Date: 2021/1/18
 * @Copyright: 版权归 Mark 所有
 * <ModifyLog>
 * @ModifyContent:
 * @Author:
 * @Date:
 * </ModifyLog>
 */
object PackageUtil {

    fun getInstalledPackages(packageManager: PackageManager): List<PackageInfo?>? {
        return packageManager.getInstalledPackages(0)
    }

    fun getPackageIcon(packageManager: PackageManager, packageName: String): Drawable? {
        return try {
            val info = packageManager.getApplicationInfo(packageName, 0)
            info.loadIcon(packageManager)
        } catch (e: PackageManager.NameNotFoundException) {
            null
        }
    }

    @SuppressLint("PackageManagerGetSignatures")
    fun getAppSignature(
        @NonNull packageManager: PackageManager,
        @NonNull packageName: String
    ): Array<String?>? {
        val result = arrayOfNulls<String>(2)
        try {
            val signs = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
                packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES).signatures
            } else {
                packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES).signingInfo.apkContentsSigners
            }
            val sign = signs[0].toByteArray()
            result[0] = parseFingerprint(sign, "MD5")
            result[1] = parseFingerprint(sign, "SHA1")
        } catch (e: Exception) {
            // Do Nothing
        }
        return result
    }

    @Throws(java.lang.Exception::class)
    private fun parseFingerprint(
        @NonNull certificateBytes: ByteArray,
        @NonNull algorithm: String
    ): String {
        val md = MessageDigest.getInstance(algorithm)
        md.update(certificateBytes)
        val digest = md.digest()
        val sb = StringBuilder()
        for (i in digest.indices) {
            if (i != 0) {
                sb.append(":")
            }
            val b: Int = digest[i].toInt() and 0xff
            val hex = Integer.toHexString(b)
            if (hex.length == 1) {
                sb.append("0")
            }
            sb.append(hex)
        }
        return sb.toString()
    }
}